<?php

namespace console\controllers;

use admin\models\Adminer;
use Carbon\Carbon;
use common\datas\PinDuoDuoCategory2023;
use common\models\db\ApiUsers;
use common\models\db\Banners;
use common\components\wtools\tools\ArrayHelper;
use common\components\wtools\tools\Security;
use common\datas\Enums;
use common\jobs\DemoJob;
use common\models\db\Adminers;
use common\models\db\Categories;
use common\models\db\Files;
use common\models\db\MpUsers;
use common\models\db\Permissions;
use common\models\db\Spus;
use common\models\db\Suppliers;
use common\models\db\Users;
use common\models\dbViews\ViewSkus;
use common\models\xunsearch\Demo;
use common\models\xunsearch\Demo1;
use common\Tools;
use yii\console\Controller;
use yii\data\ActiveDataProvider;
use yii\helpers\Console;

class TestController extends Controller
{
    private function _iniSet($isExit = false)
    {
//        ini_set("memory_limit", "12800M");
//        ini_set('max_execution_time', '0');
        var_dump(Carbon::now()->format('Y-m-d H:i:s'));
        if ($isExit) {
            Console::output('exit');
        }
    }

    /**
     * php yii test/test
     * @return void
     */
    public function actionTest()
    {
        $uniqid = uniqid('u', true);
        dd($uniqid, YII_ENV, YII_DEBUG);
    }

    /**
     * php yii test/decrypt-password
     * @return void
     */
    public function actionDecryptPassword()
    {
        $pwd_bk = Console::input("加密后的密码:");
        $decrypted = Security::thinkDecrypt($pwd_bk);
        dd($decrypted);
    }

    /**
     * 创建后台管理员
     * php yii test/add-adminer
     * @return void
     * @throws \yii\base\Exception
     */
    public function actionAddAdminer()
    {
        $adminer = new Adminers();
        $mobile = Console::input("请输入11位手机号：");
        $account_name = Console::input("请输入账户名：");
        $password = Console::input("请输入密码：");
        $adminer->mobile = $mobile;
        $adminer->account_name = $account_name;
        $adminer->generatePassword($password);
        $adminer->status = Enums::ACTIVE;
        $adminer->auth_key = Tools::generateHasDateUniqueString();
        $adminer->generateToken();
        if (!$adminer->save()) {
            dd($adminer->errors);
        }
    }

    /**
     * 修改后台管理员密码
     * php yii test/update-adminer
     * @return void
     * @throws \yii\base\Exception
     */
    public function actionUpdateAdminer()
    {
        $mobile = Console::input("请输入11位手机号：");
        $password = Console::input("请输入密码：");
        $adminer = Adminer::findByMobile($mobile);
        $adminer->generatePassword($password);
        $adminer->status = Enums::ACTIVE;
        $adminer->auth_key = Tools::generateHasDateUniqueString();
        if (!$adminer->save()) {
            dd($adminer->errors);
        }
    }

    /**
     * 添加接口用户
     * php yii test/add-api-users
     * @return void
     */
    public function actionAddApiUsers()
    {
        $count = Console::input("count:");
        $count = intval($count);
        $lastApiUser = ApiUsers::find()->orderBy(['id' => SORT_DESC])->one();
        if (!$lastApiUser) {
            $beginId = 1;
        } else {
            $beginId = $lastApiUser->id + 1;
        }
        $endId = $beginId + $count - 1;
        while ($beginId <= $endId) {
            $apiUser = new ApiUsers();
            $apiUser->id = $beginId;
            $apiUser->status = Enums::ACTIVE;
            $apiUser->generateToken();
            if (!$apiUser->save()) {
                dd($apiUser->errors);
            } else {
                var_dump($apiUser->token);
            }
            $beginId ++;
        }
    }

    /**
     * 解密密码
     * php yii test/decrypt-pwd
     * @return void
     */
    public function actionDecryptPwd()
    {
        $pwd = Console::input("密码：");
        $x = Security::thinkDecrypt($pwd);
        var_dump($x);
    }

    /**
     * 生成后台管理员token
     * php yii test/adminers-token
     * @return void
     * @throws \yii\base\Exception
     */
    public function actionAdminersToken()
    {
        $adminers = Adminers::find()->all();
        foreach ($adminers as $k => $adminer) {
            $adminer->generateToken();
            $adminer->save();
        }
    }

    public function actionTest1()
    {
        $key = "Test-test1";
        \Yii::$app->mutex->acquire($key, 30);
        var_dump(123456789);
        sleep(5);
    }

    public function actionTest2()
    {
        $job = new DemoJob();
        $job->id = 1;
        \Yii::$app->queue->push($job);
    }

    public function actionTest3()
    {
        dd(\Yii::t('app', 'Token'));
    }

    public function actionTest4()
    {
        dd(Tools::generateHasDateUniqueString());
    }

    public function actionTest5()
    {
        dd(\Yii::$app->xcxApi->guestPost('public/test', ['x' => 123456]));
    }

    public function actionTest6()
    {
        $products = Spus::find()->all();
        foreach ($products as $k => $product) {
//            $product->cover = str_replace('dev.lzdls.com', 'www.lzdls.com', $product->cover);
            $product->save();
        }
        $banners = Banners::find()->all();
        foreach ($banners as $k => $banner) {
            $banner->url = str_replace('dev.lzdls.com', 'www.lzdls.com', $banner->url);
            $banner->save();
        }
    }

    public function actionTest7()
    {
        $file = \Yii::getAlias('@uploads_root/files/20240312/b5ce8161f65cc555a6223f37d303ef38.5614.jpg');
        $file = str_replace('\\', '/', $file);
        $url = \Yii::$app->fs->uploadByFileRoot($file);
        dd($url);
    }

    /**
     * php yii test/test8
     * @return void
     */
    public function actionTest8()
    {
//        $permission = Permissions::findOne(6);
//        dd($permission->roleHasModels[0]->toArray());
//        dd($permission->roles[0]->toArray());
        $adminer = Adminers::findOne(2);
        dd($adminer->roles[0]->toArray());
    }

    /**
     * 添加测试分类
     * php yii test/test9
     * @return void
     */
    public function actionTest9()
    {
        $category = new Categories();
        for ($i = 7; $i < 25; $i ++) {
            $cate = clone $category;
            $cate->name = 'root'.$i;
            if (!$cate->save()) {
                dd($cate->errors);
            }
        }
    }

    /**
     * 添加拼多多分类
     * php yii test/test10
     * @return void
     */
    public function actionTest10()
    {
        $toCopyCates = PinDuoDuoCategory2023::$datas;
        $category = new Categories();
        foreach ($toCopyCates as $k => $v) {
            var_dump($v);
            $lv0CateName = $v[2];
            $lv0Cate = Categories::findOne(['name' => $lv0CateName]);
            if (!$lv0Cate) {
                $lv0Cate = clone $category;
                $lv0Cate->name = $lv0CateName;
                $lv0Cate->status = Enums::ACTIVE;
                $lv0Cate->is_virtual = Enums::NO;
                $lv0Cate->is_danger = Enums::NO;
                if (!$lv0Cate->save()) {
                    dd($lv0Cate->errors);
                }
            }
            $lv1CateName = $v[1];
            $lv1Cate = Categories::findOne(['name' => $lv1CateName]);
            if (!$lv1Cate) {
                $lv1Cate = clone $category;
                $lv1Cate->name = $lv1CateName;
                $lv1Cate->pid = $lv0Cate->id;
                $lv1Cate->status = Enums::ACTIVE;
                $lv1Cate->is_virtual = Enums::NO;
                $lv1Cate->is_danger = Enums::NO;
                if (!$lv1Cate->save()) {
                    dd($lv1Cate->errors);
                }
            }
            $lv2CateName = $v[0];
            $lv2Cate = Categories::findOne(['name' => $lv2CateName]);
            if (!$lv2Cate) {
                $lv2Cate = clone $category;
                $lv2Cate->name = $lv2CateName;
                $lv2Cate->pid = $lv1Cate->id;
                $lv2Cate->status = Enums::ACTIVE;
                $lv2Cate->is_virtual = Enums::NO;
                $lv2Cate->is_danger = Enums::NO;
                if (!$lv2Cate->save()) {
                    dd($lv2Cate->errors);
                }
            }
        }
    }

    /**
     * php yii test/test11
     * @return void
     */
    public function actionTest11()
    {
//        $model = new Demo();
//        $model->pid = 2;
//        $model->subject = 'hello world';
//        $model->message = 'just for testing...';
//        $model->chrono = 100;
//        $model->save();
//        dd($model);
//        dd(Demo::find()->count());

//        $x = Demo::findByQuery('subject:hello')
//            ->where(['pid' => [125, 124]])
//            ->orderBy(['pid' => SORT_DESC])
//            ->asArray()
//            ->all();
//        dd($x);

//        $demo1 = new Demo1();
//        $demo1->pid = 2;
//        $demo1->subject = '疑是地上霜';
//        $demo1->message = Tools::generateHasDateUniqueString();
//        $demo1->sort = 2;
//        $demo1->save();
//        dd($demo1);

        $x = Demo1::findByQuery('subject:床')
            ->orderBy(['pid' => SORT_DESC])
            ->asArray()
            ->all();
        dd($x);
    }

    /**
     * php yii test/test12
     * @desc when测试无效
     * @return void
     * @throws \yii\db\Exception
     */
    public function actionTest12()
    {
        $query = Users::find();
        $query->when(true, function ($query) {
            $query->createCommand()->rawSql;
        });
    }

    /**
     * php yii test/test13
     * @desc 测试微信头像下载
     * @return void
     */
    public function actionTest13()
    {
        $wxAvatar = 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132';
        dd(base64_encode(file_get_contents($wxAvatar)));
    }

    /**
     * php yii test/test14
     * @desc mpUser测试jwtToken生成
     * @throws \Exception
     * @return void
     */
    public function actionTest14()
    {
        $mpUserId = Console::input("mpUserId:");
        if (!$mpUserId) {
            dd('mpUserId不能为空');
        }
        $mpUser = MpUsers::findOne($mpUserId);
        $jwtTokenArr = $mpUser->generateJwtToken();
//        dd($jwtToken);
        $tokenArr = MpUsers::getJwtToken($jwtTokenArr);
        $tokenInfo = [];
        $tokenInfo['jwtToken'] = $tokenArr['jwt']['jwtToken'];
        $tokenInfo['encryptedMpUserKey'] = $tokenArr['encryptedMpUserKey'];
        $tokenInfo['mpUser'] = MpUsers::getFilterShow($tokenArr['mpUser']);
//        var_dump($jwtTokenArr, $tokenArr['jwt']);
        $token = Tools::toJson($tokenInfo);
//        $res = \Yii::$app->xcxApiTool->setJwtToken($jwtTokenArr)->post('/user/center/index');
//        var_dump($res);
        echo($token);exit;
    }

    /**
     * php yii test/test15
     * @return void
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\db\Exception
     */
    public function actionTest15()
    {
        $this->_iniSet();
        $file = Files::find()->one();
        dd($file->abUrl);
    }

    /**
     * php yii test/test16
     * @return void
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\db\Exception
     */
    public function actionTest16()
    {
        $this->_iniSet();
        $query = Files::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 10,
                'page' => 1,
            ],
        ]);
        $dataProvider->prepare();
        var_dump($dataProvider->pagination->pageCount);
        var_dump($dataProvider->totalCount);
        var_dump($dataProvider->pagination->pageSize);
    }

    /**
     * php yii test/test17
     * @return void
     */
    public function actionTest17()
    {
        $this->_iniSet();
        $file = \Yii::getAlias('@storage_root/1066.jpg');
        $fileContent = file_get_contents($file);
//        $base64 = base64_encode($fileContent);
//        dd(md5($fileContent), md5_file($file));
        dd(strlen($fileContent), filesize($file));
    }
}
